<template>
  <div>
    <a-modal
      :visible="props.visible"
      title="修改商品信息"
      @ok="submit"
      @cancel="closeEditOne"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="商品名称">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="商品价格">
          <a-input-number
            v-model:value="editForm.price"
            :min="0"
            :max="999999"
          />
        </a-form-item>
        <a-form-item label="商家">
          <a-input v-model:value="editForm.merchant" />
        </a-form-item>
        <a-form-item label="发布时间">
          <a-date-picker v-model:value="editForm.publishDate" />
        </a-form-item>
        <a-form-item label="商品分类">
          <a-input v-model:value="editForm.classify" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import { defineComponent, reactive, watch } from 'vue'
import { handleResult } from '../../helpers/utils'
import { goodService } from '../../services'
import moment from 'moment'
export default defineComponent({
  props: {
    visible: Boolean,
    good: Object
  },
  setup (props, ctx) {
    /** 编辑商品表单数据 */
    const editForm = reactive({
      name: '',
      price: 0,
      merchant: '',
      publishDate: '',
      classify: ''
    })

    /** 提交修改商品表单时事件 */
    const submit = async () => {
      const res = await goodService.updateGood({
        id: props.good._id,
        name: editForm.name,
        price: editForm.price,
        merchant: editForm.merchant,
        publishDate: editForm.publishDate.valueOf(),
        classify: editForm.classify
      })
      handleResult(res).success(({ msg, data }) => {
        ctx.emit('update', data)
        message.success(msg)
        closeEditOne()
      })
    }

    /** 关闭添加商品弹框 */
    const closeEditOne = () => {
      ctx.emit('update:visible', false)
    }

    watch(
      () => props.good,
      current => {
        Object.assign(editForm, current)
        editForm.publishDate = moment(Number(editForm.publishDate))
      }
    )

    return {
      editForm,
      submit,
      props,
      closeEditOne
    }
  }
})
</script>

<style lang="scss" scoped></style>
